'''
截取动漫人物头部信息
'''
import logging
import time

import cv2  # 需提前在你的python环境下安装opencv包
import os.path
from glob import glob

indir = r"D:\git\unfinished\download_videos\anime\old_men"
outdir = r"D:\BaiduNetdiskDownload\face66\boys"
if not os.path.exists(outdir):
    os.makedirs(outdir)
imgSize = [256, 256]


logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s %(levelname)s: %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S',
    filename=os.path.join("log", "anime_" + str(time.time()).replace(".", "_") + ".log")
)


def detect(filename, dirout, cascade_file="lbpcascade_animeface.xml"):
    if not os.path.isfile(cascade_file):  # lbpcascade_animeface.xml文件可在github上面找到，就是一个巨长的xml格式代码，表示看不懂。
        raise RuntimeError("%s: not found" % cascade_file)
    cascade = cv2.CascadeClassifier(cascade_file)

    image = cv2.imread(filename)
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    gray = cv2.equalizeHist(gray)

    faces = cascade.detectMultiScale(gray,
                                     # detector options
                                     scaleFactor=1.1,
                                     minNeighbors=5,
                                     minSize=(64, 64))
    if len(faces) != 0:
        for i, (x, y, w, h) in enumerate(faces):
            face = image[y: y + h, x:x + w, :]
            face = cv2.resize(face, tuple(imgSize))
            save_filename = '%s-%d.jpg' % (os.path.basename(filename).split('.')[0], i)
            cv2.imwrite(os.path.join(dirout, save_filename), face)  # 写入文件
        print(f"成功转换{filename}")
    else:
        print(f"没有获取到照片{filename}")


def catch_anime_faces(dirin, dirout):
    '''
    截取动漫头像部分
    :param dirin:
    :param dirout:
    :return:
    '''
    if os.path.exists(dirout) is False:
        os.makedirs(dirout)
    file_list = glob(os.path.join(dirin, '*.*'))
    for filename in file_list:
        print(filename)
        try:
            detect(filename, dirout)
        except Exception as err:
            print(err)


if __name__ == '__main__':
    catch_anime_faces(indir, outdir)
